﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Prism.Regions;
using RecipeDemo.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RecipeDemo.ViewModels
{
    public partial class RecipeViewModel : ObservableObject
    {
        private readonly IRegionManager _regionManager;
        private readonly ScanPointRepository _scanPointRepo;

        [ObservableProperty]
        private ObservableCollection<ScanPointItem> _scanPointItems = new();

        [ObservableProperty]
        private ScanPointItem _selectedScanPointItem;

        public RecipeViewModel(IRegionManager regionManager, ScanPointRepository scanPointRepo)
        {
            _regionManager = regionManager;
            _scanPointRepo = scanPointRepo;

            ScanPointItem item1 = new ScanPointItem
            {
                DisplayName = "Point 1",
                ScanPoint = new ScanPointViewModel()
            };
            // 初始化示例数据
            ScanPointItems.Add(item1);
            _scanPointRepo.AddOrUpdate(item1); // 同步到仓库
            ScanPointItem item2 = new ScanPointItem
            {
                DisplayName = "Point 2",
                ScanPoint = new ScanPointViewModel()
            };
            // 初始化示例数据
            ScanPointItems.Add(item2);
            _scanPointRepo.AddOrUpdate(item2); // 同步到仓库
        }

        [RelayCommand]
        private void OpenEditor()
        {
            if (SelectedScanPointItem == null) return;

            var parameters = new NavigationParameters
            {
                { "ScanPointId", SelectedScanPointItem.Id }
            };
            _regionManager.RequestNavigate("MainRegion", "MPEditorView", parameters);
        }

        [RelayCommand]
        private void SaveAllScanPoints()
        {
            try
            {
                string json = _scanPointRepo.ExportToJson();
                File.WriteAllText("scanpoints.json", json);
            }
            catch (Exception ex)
            {
                // 使用EventAggregator发布错误消息（需注入）
            }
        }
    }
}